package com.yokead.controller.admin;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.jiangzeyin.StringUtil;
import cn.jiangzeyin.common.JsonMessage;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yokead.common.OrderBaseControl;
import com.yokead.service.order.OrderService;
import com.yokead.service.order.ProductService;
import com.yokead.system.log.SystemLog;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.*;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.WebApplicationContext;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Set;

/**
 * Created by jiangzeyin on 2017/4/28.
 */
@Controller
@Scope(value = WebApplicationContext.SCOPE_SESSION)
public class ExportControl extends OrderBaseControl {

    @Resource
    private OrderService orderService;

    @Resource
    private ProductService productService;

    @RequestMapping(value = "export.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String export() {
        return "admin/list/export";
    }


    @RequestMapping(value = "export_more.html", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String export_more() throws IOException {
        setAttribute("array", productService.getUserAll(userName));
        return "admin/export_more";
    }

    @RequestMapping(value = "exportExcel_more.html", produces = MediaType.TEXT_HTML_VALUE)
    @ResponseBody
    public String exportExcel_more(String date) {
        String fileName = "多个订单信息.xls";
        String[] plist = getParameters("plist");
        return exportExcelRun(fileName, null, date, null, plist);
    }

    @RequestMapping(value = "exportExcel.html", produces = MediaType.TEXT_HTML_VALUE)
    @ResponseBody
    public String exportExcel(String product, String date, String product_name, String gzid) {
        String fileName = "订单信息.xls";
        return exportExcelRun(fileName, gzid, date, product_name, product);
    }

    private String exportExcelRun(String fileName, String gzid, String date, String product_name, String... product) {
        if (product == null || product.length <= 0) {
            return "请选择需要导出的产品";
        }
        WritableWorkbook workbook;
        try {
            HttpServletResponse response = getResponse();
            // 定义输出流，以便打开保存对话框______________________begin
            OutputStream os = response.getOutputStream();// 取得输出流
            response.reset();// 清空输出流
            response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes(), "ISO8859-1"));
            // 设定输出文件头
            response.setContentType("application/msexcel");// 定义输出类型
            //** **********创建工作簿************ */
            workbook = Workbook.createWorkbook(os);
        } catch (IOException e) {
            SystemLog.ERROR().error("导出异常", e);
            return "导出异常：-102";
        }
        out:
        for (int i = 0, len = product.length; i < len; i++) {
            String result;// = "系统提示：Excel文件导出成功！";
            // 以下开始输出到EXCEL
            try {
                String item = product[i];
                item = convertFilePath(item);
                //** **********创建工作表************ */
                JSONObject productInfo = productService.getProductInfoJsonObj(userName, item);
                if (productInfo == null) {
                    continue;
                }
                String title = productInfo.getString("title");
                if (StringUtil.isEmpty(title)) {
                    title = "订单(" + item + ")";
                }
                WritableSheet sheet = workbook.getSheet(title);
                if (sheet != null) {
                    title += "(" + item + ")";
                }
                sheet = workbook.createSheet(title, i);
                JSONObject jsonOrder = orderService.getProductColumn(userName, item);
                if (jsonOrder == null) {
                    result = "系统提示：Excel文件导出失败：coe=501！";
                    sheet.addCell(new Label(0, 0, result, wcf_left));
                    continue;
                }
                JSONArray jsonArray = jsonOrder.getJSONArray("columns");
                if (jsonArray == null || jsonArray.size() <= 0) {
                    result = "系统提示：Excel文件导出失败：coe=502！";
                    sheet.addCell(new Label(0, 0, result, wcf_left));
                    continue;
                }
                HashMap<String, String> map = new HashMap<>();
                for (int j = 0, lenj = jsonArray.size(); j < lenj; j++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(j);
                    map.put(jsonObject.getString("name"), jsonObject.getString("desc"));
                }
                // 定义输出流，以便打开保存对话框_______________________end

                //** **********设置纵横打印（默认为纵打）、打印纸***************** */
                jxl.SheetSettings sheetset = sheet.getSettings();
                sheetset.setProtected(false);
                //** ***************以下是EXCEL开头大标题，暂时省略********************* */
                // sheet.mergeCells(0, 0, colWidth, 0);
                // sheet.addCell(new Label(0, 0, "XX报表", wcf_center));
                //** ***************以下是EXCEL第一行列标题********************* */
                Collection<String> head = map.values();
                Object[] tiltesCloums = head.toArray();
                for (int j = 0; j < tiltesCloums.length; j++) {
                    sheet.addCell(new Label(j, 0, tiltesCloums[j].toString(), wcf_center));
                }
                //** ***************以下是EXCEL正文数据********************* */
                Set<String> keyNames = map.keySet();
                Object[] keyNames_ = keyNames.toArray();
                int count = 1;
                int pageNo = 1;
                while (true) {
                    String jsonStr = orderService.doSelect(userName, item, pageNo, 10, gzid, 0, date, product_name, null);
                    JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                    int code = jsonObject.getIntValue(JsonMessage.CODE);
                    if (code != 200) {
                        String msg = jsonObject.getString(JsonMessage.MSG);
                        sheet.addCell(new Label(0, 0, msg, wcf_left));
                        break out;
                    }
                    JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                    int totalPage = jsonObject1.getIntValue("totalPage");
                    JSONArray array = jsonObject1.getJSONArray("results");
                    if (array != null) {
                        for (int k = 0; k < array.size(); k++) {
                            JSONObject obj = array.getJSONObject(k);
                            int j = 0;

                            for (Object object : keyNames_) {
                                String string = object.toString();
                                if ("createTime".equals(string)) {
//                                    DateUtil.formatTimeStamp(null, );
                                    String time = new DateTime(obj.getIntValue(string) * 1000).toString(DatePattern.NORM_DATETIME_PATTERN);
                                    sheet.addCell(new Label(j, count, time, wcf_left));
                                } else {
                                    sheet.addCell(new Label(j, count, obj.getString(string), wcf_left));
                                }
                                j++;
                            }
                            count++;
                        }
                    }
                    if (totalPage > pageNo) {
                        pageNo++;
                        continue;
                    }
                    break;
                }

            } catch (Exception e) {
                // result = "系统提示：Excel文件导出失败，原因：" + e.toString();
                SystemLog.ERROR().error("生成失败", e);
            }
        }
        //** **********将以上缓存中的内容写到EXCEL文件中******** */
        try {
            workbook.write();
            workbook.close();
        } catch (IOException | WriteException e) {
            SystemLog.ERROR().error("导出异常", e);
            return "导出异常：-103";
        }
        //** *********关闭文件************* */

        return "导出成功";
    }


    /**
     * @param fileName
     * @param product
     * @return
     * @author jiangzeyin
     * date 2016-11-16
     */
    private String exportExcelRun(String fileName, String gzid, String date, String product_name, String product) {
        return exportExcelRun(fileName, gzid, date, product_name, new String[]{product});
    }

    /**
     * ***********设置单元格字体**************
     */
    private static WritableFont NormalFont = new WritableFont(WritableFont.ARIAL, 10);
    private static WritableFont BoldFont = new WritableFont(WritableFont.ARIAL, 10, WritableFont.BOLD);

    /**
     * ***********以下设置三种单元格样式，灵活备用************
     */
    // 用于标题居中
    private static WritableCellFormat wcf_center = new WritableCellFormat(BoldFont);
    // 用于正文居左
    private static WritableCellFormat wcf_left = new WritableCellFormat(NormalFont);
    //private static HashMap<String, String> tableHead = new HashMap<>();
    //private static String tableColumns = "";

    static {
        try {
            wcf_center.setBorder(Border.ALL, BorderLineStyle.THIN);// 线条
            wcf_center.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
            wcf_center.setAlignment(Alignment.CENTRE); // 文字水平对齐
            wcf_center.setWrap(false); // 文字是否换行

            wcf_left.setBorder(Border.NONE, BorderLineStyle.THIN); // 线条
            wcf_left.setVerticalAlignment(VerticalAlignment.CENTRE); // 文字垂直对齐
            wcf_left.setAlignment(Alignment.LEFT); // 文字水平对齐
            wcf_left.setWrap(false); // 文字是否换行
        } catch (WriteException e) {
            // TODO Auto-generated catch block
            SystemLog.ERROR().error("初始化失败", e);
        }
    }
}
